package com.aloda.aop;

import com.aloda.annotation.AdminAuthCheck;
import com.aloda.constant.ErrorCode;
import com.aloda.context.AdminBaseContext;
import com.aloda.entity.Emp;
import com.aloda.exception.BaseException;
import com.aloda.mapper.EmpMapper;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AdminAuthAspect {

    @Resource
    private EmpMapper empMapper;

    /**
     * 管理端权限校验
      * @param joinPoint
     * @param adminAuthCheck
     * @return
     * @throws Throwable
     */
    @Around("@annotation(adminAuthCheck)")
    public Object authCheck(ProceedingJoinPoint joinPoint, AdminAuthCheck adminAuthCheck) throws Throwable {
        // 获取校验权限
        Integer mustRole = adminAuthCheck.mustRole();
        // 获取当前登录用户
        Long currentId = AdminBaseContext.getCurrentId();
        Emp emp = empMapper.selectById(currentId);
        if (!mustRole.equals(emp.getAuth())) {
            throw new BaseException(ErrorCode.FORBIDDEN_ERROR);
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}
